﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace FileDownload
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码和配置文件中的类名“Service1”。
    public class Service1 : IService1
    {
        public string DownLoadRecipe(string recipeName)
        {
            string[] strCode = new string[] { "1001", "1002", "1003", "1004", "1005" };
            string resultCode = "";
            try
            {
                KeyUpper.SetState(KeyUpper.VirtualKeys.VK_CAPITAL, true);
                bool status = false;
                //string netDir = @"\\10.80.88.180\test";
                //string netDir = @"\\127.0.0.1\Mytest";
                //string myDir = @"D:\TEST";
                string netDir = ConfigurationManager.AppSettings["netAddress"];
                string myDir = ConfigurationManager.AppSettings["localAddress"];
                string userName = ConfigurationManager.AppSettings["userName"];
                string password = ConfigurationManager.AppSettings["password"];
                //网盘文件夹路径未配置（1001）
                if (string.IsNullOrEmpty(netDir))
                {
                    resultCode = "1001";
                    throw new Exception("1001");
                }
                //本地文件夹路径未配置（1002）
                if (string.IsNullOrEmpty(netDir))
                {
                    resultCode = "1002";
                    throw new Exception("1002");
                }
                DirectoryInfo theFolder = new DirectoryInfo(netDir);
                //网盘文件夹路径不存在（1003）
                if (!theFolder.Exists)
                {
                    resultCode = "1003";
                    throw new Exception("1003");
                }

                //连接共享文件夹
                status = FileShare.connectState(netDir, userName, password);
                if (status)
                {
                    
                    DirectoryInfo MyFolder = new DirectoryInfo(myDir);
                    //本地文件夹路径不存在（1004）
                    if (!MyFolder.Exists)
                    {
                        resultCode = "1004";
                        throw new Exception("1004");
                    }
                    //遍历本地文件夹，删除所有文件
                    foreach (FileSystemInfo nextDir in MyFolder.GetFileSystemInfos())
                    {

                        if (nextDir is DirectoryInfo)            //判断是否文件夹
                        {
                            if (nextDir.Name != "Example")
                            {
                                DirectoryInfo subdir = new DirectoryInfo(nextDir.FullName);
                                subdir.Delete(true);          //删除子目录和文件
                            }
                        }
                        else
                        {
                            File.Delete(nextDir.FullName);      //删除指定文件
                        }

                    }
                    //先测试读文件，把目录路径与文件名连接
                    string filePath = theFolder.ToString() + "\\"+ recipeName;
                    ////文件名不存在（1005）
                    
                    //bool fileExists = File.Exists(filename);
                    //if (!fileExists)
                    //{
                    //    resultCode = "1005";
                    //    throw new Exception("1005");
                    //}
                    string createPath = MyFolder.ToString();
                    CopyDirectory(filePath, createPath);
                    //foreach (FileSystemInfo nextDir in theFolder.GetFileSystemInfos())
                    //{

                    //    if (nextDir is DirectoryInfo)            //判断是否文件夹
                    //    {
                    //        if (nextDir.Name != "Example")
                    //        {
                    //            DirectoryInfo subdir = new DirectoryInfo(nextDir.FullName);
                    //            subdir.Create();          //删除子目录和文件
                    //        }
                    //    }
                    //    else
                    //    {
                    //        filePath += nextDir.Name;
                    //        createPath += nextDir.Name;
                    //        File.Copy(filePath, createPath);
                    //    }
                    //}

                    //File.Copy(filename, createPath);
                    resultCode = "success";
                }
                else
                {
                    //ListBox1.Items.Add("未能连接！");
                }
            }
            catch (Exception e)
            {
                if (!strCode.Contains(resultCode))
                {
                    resultCode = e.Message + e.StackTrace;
                }
            }
            return resultCode;
        }
        private static void CopyDirectory(string srcPath, string desPath)
        {
            string folderName = srcPath.Substring(srcPath.LastIndexOf("\\") + 1);
            string desfolderdir = desPath + "\\" + folderName;
            if (desPath.LastIndexOf("\\") == (desPath.Length - 1))
            {
                desfolderdir = desPath + folderName;
            }
            string[] filenames = Directory.GetFileSystemEntries(srcPath);
            foreach (string file in filenames)
            {
                if (Directory.Exists(file))
                {
                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);
                    //string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    if (!Directory.Exists(currentdir))
                    {
                        Directory.CreateDirectory(currentdir);
                    }
                    CopyDirectory(file, desfolderdir);
                }
                else
                {
                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);
                    srcfileName = desfolderdir + "\\" + srcfileName;
                    if (!Directory.Exists(desfolderdir))
                    {
                        Directory.CreateDirectory(desfolderdir);
                    }

                    File.Copy(file, srcfileName);
                }
            }
        }
        //public string GetData(int value)
        //{
        //    return string.Format("You entered: {0}", value);
        //}

        //public CompositeType GetDataUsingDataContract(CompositeType composite)
        //{
        //    if (composite == null)
        //    {
        //        throw new ArgumentNullException("composite");
        //    }
        //    if (composite.BoolValue)
        //    {
        //        composite.StringValue += "Suffix";
        //    }
        //    return composite;
        //}
    }
}
